//
//  ViewController.swift
//  Swift_MyLive
//
//  Created by admin on 16/9/7.
//  Copyright © 2016年 admin. All rights reserved.
//

import UIKit

let WIDTH = UIScreen.main.bounds.size.width
let HEIGHT = UIScreen.main.bounds.size.height

let url = "http://cbox.cntv.cn/json2015/fenleierjiye/xinwen/jinpingtuijinamore/index.json"



class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
   /* @available(iOS 6.0, *)
    public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
    }*/

    
    var dataArray : NSMutableArray?
    var colctionV : UICollectionView?

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
      self.title = "新闻"
        self.setTableView()
        self.loadWebData()
    }
    
    func setTableView()
    {
        dataArray = NSMutableArray()
        let vcf = UICollectionViewFlowLayout()
        vcf.scrollDirection = .vertical
        vcf.itemSize = CGSize(width: WIDTH/2-1, height: 130)
        vcf.minimumInteritemSpacing = 1  //cell 之间的横向间距
        vcf.minimumLineSpacing = 1      //纵向间距
        
        colctionV = UICollectionView(frame: CGRect(x: 0, y: 64, width: WIDTH, height: HEIGHT-64-49), collectionViewLayout: vcf)
        colctionV!.delegate = self
        colctionV!.dataSource = self
        colctionV!.backgroundColor = UIColor.white
        
         colctionV!.register(LiveCell().classForCoder, forCellWithReuseIdentifier: "cell")
        self.automaticallyAdjustsScrollViewInsets = false
        self.view.addSubview(colctionV!)
        
        colctionV!.addPullToRefresh(actionHandler: {
            
            self.loadWebData()
        })
        
        
    }
    
    func loadWebData()
    {
     
         SVProgressHUD.show()
        AppLicationInfo.shareInstance.GET(getUrl: url, parame: nil, isHead: false, success: { (data) in
            
            print(data)
            
            let dataDic = data.dictionaryForKey(key: "data")
            let itemList = dataDic.arrayForKey(key: "itemList")
            
            for dict in itemList
            {
                let data = DataModel()
                data.setModelData(dic: dict as! NSDictionary)
                
                self.dataArray?.add(data)
            }
            self.colctionV!.reloadData()
            
            self.colctionV!.pullToRefreshView.stopAnimating()
            SVProgressHUD.dismiss()

        }) { (data, error) in
            self.colctionV!.pullToRefreshView.stopAnimating()
            SVProgressHUD.dismiss()
            print("网络错误：\(String(describing: data))")
        }
    }
    
    private func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return self.dataArray!.count
    }
    
    internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        var cell = LiveCell()
         cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath as IndexPath) as! LiveCell
       let dataM = self.dataArray?[indexPath.row]
        
        cell.setCellData(dataM: dataM as! DataModel)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let dataM = self.dataArray?[indexPath.row]
        
        let playVc = PlayerViewController()
        playVc.setDataM(dataM: dataM as! DataModel)
        self.popViewController(controller: playVc)
    }
    
    func popViewController(controller:UIViewController)
    {
        
        controller.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(controller, animated: true)
    }

    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    


}


extension NSDictionary {
    
    func dictionaryForKey(key:String) -> NSDictionary
    {
        var value : AnyObject?
        value = self.object(forKey: key) as AnyObject?
       // value = self[key] as! [[NSObject:AnyObject]] as AnyObject?
        if value is NSDictionary
        {
            return value as! NSDictionary
        }
        
        return NSDictionary()
    }
    
    func intForKey(key:String) -> Int
    {
       let value = self[key]
        if value is String || value is NSNumber {
            
            return value as! Int
        }
        return Int()
    }
    
    func stringForKey(key:String) -> String
    {
        let value = self[key]
        if value is String {
            
            return value as! String
            
        }else if (((value as AnyObject).responds(to: #selector(NSObject.description as () -> String))))
        {
            return ((value as AnyObject).description)!
        }
        return ""
    }
    
    func arrayForKey(key:String) -> NSArray
    {
        let value = self[key]
        if value is NSArray {
            
            return value as! NSArray
        }
        return NSArray()
    }
}

extension UIImageView {
    
    
    func loadImgUrl(imgUrl : String){
        
        let disp = DispatchQueue.global()
        disp.async {
            
            let URL:NSURL = NSURL(string: imgUrl)!
            let data = NSData.init(contentsOf: URL as URL)
            if data != nil {
                
                let image = UIImage.init(data: data! as Data)
                //主线程中刷新UI
                DispatchQueue.main.async {
                    //刷新主UI
                    self.image = image
                    
                }
              
            }
            
        }

    }
}






